package com.lovebridge.service.impl;


import com.jiehoo.ooqi.From;
import com.jiehoo.ooqi.QueryInfo;
import com.jiehoo.ooqi.SearchResult;
import com.lovebridge.SystemManager;
import com.lovebridge.model.Base;
import com.lovebridge.service.IService;


public abstract class BaseService implements IService {

    public void delete(Base object) throws Exception {
        SystemManager.getPersist().delete(object);
    }

    public void create(Base object) throws Exception {
        SystemManager.getPersist().insert(object);
    }

    public void update(Base object) throws Exception {
        SystemManager.getPersist().update(object);
    }

    public SearchResult query(Class c) {
        QueryInfo query = new QueryInfo();
        query.setGetTotalRows(true);
        query.setPageSize(25);
        query.addFrom(new From(c, c.getName().substring(0, 1).toLowerCase()));
        return query(c, query);
    }

    public SearchResult query(Class c, QueryInfo query) {
        SearchResult result = new SearchResult();
        result.setPageResult(SystemManager.getPersist().readList(c, query.getQL()));
        if (query.isGetTotalRows()) {
            result.setTotalRows(SystemManager.getPersist().read(Integer.class, query.getCountQL()));
        } else {
            result.setTotalRows(result.getPageResult().size());
        }
        return result;
    }
}
